package com.yyjj.my.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aries.ui.view.title.TitleBarView;
import com.aries.ui.widget.progress.UIProgressDialog;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.event.IEvent;
import com.vise.xsnow.event.Subscribe;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.request.PostRequest;
import com.yyjj.my.R;
import com.yyjj.my.api.ApiConstant;
import com.yyjj.my.api.UrlContant;
import com.yyjj.my.entity.UpDataUserInfoEntity;
import com.yyjj.my.entity.UpLoadEntity;

import java.io.File;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import tech.com.commoncore.Config;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.basecomponent.ServiceFactory;
import tech.com.commoncore.event.PersonalChangeEvent;
import tech.com.commoncore.manager.GlideManager;
import tech.com.commoncore.utils.FastUtil;
import tech.com.commoncore.utils.FileUtils;
import tech.com.commoncore.utils.OnNoDoubleClickListener;
import tech.com.commoncore.utils.ToastUtil;
import tech.com.commoncore.widget.photoPicker.MyPhotoPickerActivity;

public class SetUpActivity extends BaseTitleActivity implements EasyPermissions.PermissionCallbacks {
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 1;

    //    @BindView(R2.id.titleBar_headFastLib)
    TitleBarView titleBarHeadFastLib;
    //    @BindView(R2.id.setUp_rl1)
    RelativeLayout setUpRl1;
    //    @BindView(R2.id.setUp_rl2)
    RelativeLayout setUpRl2;
    //    @BindView(R2.id.setUp_rl3)
    RelativeLayout setUpRl3;
    //    @BindView(R2.id.head_iv_more)
    ImageView headIvMore;
    //    @BindView(R2.id.head_iv)
    ImageView headIv;
    //    @BindView(R2.id.nikeName_iv_more)
    ImageView nikeNameIvMore;
    //    @BindView(R2.id.nikeName_tv)
    TextView nikeNameTv;
    //    @BindView(R2.id.signature)
    TextView signature;
    //    @BindView(R2.id.signature_iv_more)
    ImageView signatureIvMore;
    //    @BindView(R2.id.signature_tv)
    TextView signatureTv;
    private UIProgressDialog mProgressDialog;

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText(getResources().getString(R.string.my_mine_ziliao));
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_set_up;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        titleBarHeadFastLib = findViewById(R.id.titleBar_headFastLib);
        setUpRl1 = findViewById(R.id.setUp_rl1);
        setUpRl2 = findViewById(R.id.setUp_rl2);
        setUpRl3 = findViewById(R.id.setUp_rl3);
        headIvMore = findViewById(R.id.head_iv_more);
        headIv = findViewById(R.id.head_iv);
        nikeNameIvMore = findViewById(R.id.nikeName_iv_more);
        nikeNameTv = findViewById(R.id.nikeName_tv);
        signature = findViewById(R.id.signature);
        signatureIvMore = findViewById(R.id.signature_iv_more);
        signatureTv = findViewById(R.id.signature_tv);


        if (ServiceFactory.getInstance().getLoginService().getCurrentUser() != null) {
            initUser();
        }


        setOnClick();
    }

    private void setOnClick() {
        setUpRl1.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                choicePhotoWrapper();
            }
        });
        setUpRl2.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                FastUtil.startActivity(SetUpActivity.this, NikeNameActivity.class);
            }
        });
        setUpRl3.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                FastUtil.startActivity(SetUpActivity.this, LabelActivity.class);
            }
        });
    }

//    @OnClick({R2.id.setUp_rl1, R2.id.setUp_rl2, R2.id.setUp_rl3})
//    public void onClick(View view) {
//        int i = view.getId();
//        if (i == R.id.setUp_rl1) {
//            choicePhotoWrapper();
//
//        } else if (i == R.id.setUp_rl2) {
//            FastUtil.startActivity(SetUpActivity.this, NikeNameActivity.class);
//
//        } else if (i == R.id.setUp_rl3) {
//            FastUtil.startActivity(SetUpActivity.this, LabelActivity.class);
//
//        }
//    }

    @Subscribe
    public void onChange(IEvent event) {
        if (event instanceof PersonalChangeEvent) {
            initUser();
        }
    }

    private void initUser() {

        if (ServiceFactory.getInstance().getLoginService().getCurrentUser() != null) {
            if (!ServiceFactory.getInstance().getLoginService().getCurrentUser().getNickName().equals("")) {
                nikeNameTv.setText(ServiceFactory.getInstance().getLoginService().getCurrentUser().getNickName());
            } else {
                nikeNameTv.setText(ServiceFactory.getInstance().getLoginService().getCurrentUser().getMobile());
            }
            GlideManager.loadCircleImg(ServiceFactory.getInstance().getLoginService().getCurrentUser().getAvatar(), headIv, R.mipmap.head);
            if (!ServiceFactory.getInstance().getLoginService().getCurrentUser().getSignature().equals("")) {
                nikeNameTv.setText(ServiceFactory.getInstance().getLoginService().getCurrentUser().getSignature());
            } else {
                signatureTv.setText(getResources().getString(R.string.my_sin));
            }
        }



//        ViseHttp.GET(UrlContant.USERINFO)
//                .addHeader("XX-Token", ServiceFactory.getInstance().getLoginService().getCurrentUser().getToken())
//                .addHeader("XX-Device-Type", "android")
//                .request(new ACallback<UserInfoEntity>() {
//                    @Override
//                    public void onSuccess(UserInfoEntity data) {
//                        Log.d("setUp", data.toString());
//
//
//                        if (data.getCode() == 1) {
//                            if (!data.getData().getUser_nickname().equals("")) {
//                                nikeNameTv.setText(data.getData().getUser_nickname());
//                            } else {
//                                nikeNameTv.setText(data.getData().getMobile());
//                            }
//                            GlideManager.loadCircleImg(data.getData().getAvatar(), headIv, R.mipmap.logo);
//                            if (!data.getData().getSignature().equals("")) {
//                                signatureTv.setText(data.getData().getSignature());
//                            } else {
//                                signatureTv.setText("说点什么吧..");
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onFail(int errCode, String errMsg) {
//                        Log.d("setUponFail", errMsg);
//                    }
//                });

    }

    //-------------------------------------图片选择器开始--------------------------------------
    //上传图片
    private void upLoadPic(String picUrl) {
        showLoading();
        File file = FileUtils.getFileByPath(picUrl);
        ViseHttp.UPLOAD(UrlContant.UPDATA_IMG)
                .baseUrl(ApiConstant.C_URL)
                .addHeader("XX-Token", ServiceFactory.getInstance().getLoginService().getCurrentUser().getToken())
                .addHeader("XX-Device-Type", "android")
                .addFile("file", file)
                .request(new ACallback<UpLoadEntity>() {

                    @Override
                    public void onSuccess(UpLoadEntity data) {
                        if (data.getCode() == 1) {
                            String url = data.getData().getComplete_url();
                            updateUserInfo(url, "", "");
                            ToastUtil.show(getResources().getString(R.string.my_mine_up_suc));
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        hideLoading();
                        ToastUtil.show(getResources().getString(R.string.my_mine_up_fail));
                    }
                });

    }

    private void updateUserInfo(String url, String user_nickname, String signature) {
        PostRequest postRequest = ViseHttp.POST(UrlContant.UPDATA_USERINFO)
                .baseUrl(tech.com.commoncore.constant.ApiConstant.BASE_URL)
                .addHeader("XX-Token", ServiceFactory.getInstance().getLoginService().getCurrentUser().getToken())
                .addHeader("XX-Device-Type", "android");
        if (!url.equals("")) postRequest.addParam("avatar", url);
        if (!user_nickname.equals("")) postRequest.addParam("user_nickname", user_nickname);
        if (!signature.equals("")) postRequest.addParam("signature", signature);
        postRequest.request(new ACallback<UpDataUserInfoEntity>() {

            @Override
            public void onSuccess(UpDataUserInfoEntity data) {
                hideLoading();
                ToastUtil.show(data.getMsg());
                if (data.getCode() == 1) {
                    BusManager.getBus().post(new PersonalChangeEvent());
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                Log.d("BaseEntity", errMsg);
                hideLoading();
            }
        });
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Config.PHOTO_PATH);
            Intent photoPickerIntent = new MyPhotoPickerActivity.IntentBuilder(this)
                    .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                    .selectedPhotos(mPhotoLayout.getData()) // 当前已选中的图片路径集合
                    .maxChooseCount(1) // 图片选择张数的最大值
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.tip_photo_permissions_request), PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            ToastUtil.show(R.string.tip_photo_permissions_denied);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
//            mPhotoLayout.setData(MyPhotoPickerActivity.getSelectedPhotos(data));
            upLoadPic(MyPhotoPickerActivity.getSelectedPhotos(data).get(0)); //保存图片

        }
    }


    public void showLoading() {
        if (mProgressDialog == null) {
            mProgressDialog = new UIProgressDialog.WeBoBuilder(this)
                    .setMessage(getResources().getString(R.string.my_mine_up_postting))
                    .setCancelable(false)
                    .create();
        }
        mProgressDialog.setDimAmount(0.6f)
                .show();
    }

    public void hideLoading() {
        if (mProgressDialog != null) {
            mProgressDialog.hide();
        }
    }


    //-------------------------------------图片选择器结束----------------------------------------


}
